<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { checkAgv, checkCam, checkDb, checkFs } from "@/axios/api.ts";
import axios from "axios";

interface CheckItem {
  id: string;
  text: string;
  status: 'loading' | 'success' | 'error';
  isExpanded: boolean;
  solution: string;
  errorMessage?: string;
  apiCall: (signal: AbortSignal) => Promise<any>;
}

const checks = ref<CheckItem[]>([
  {
    id: 'fs',
    text: '正在检查系统文件完整性',
    status: 'loading',
    isExpanded: false,
    solution: '解决方案：请重新安装本系统。',
    apiCall: checkFs
  },
  {
    id: 'db',
    text: '正在检测数据库系统连接',
    status: 'loading',
    isExpanded: false,
    solution: '解决方案：请检查数据库连接设置是否正确。',
    apiCall: checkDb
  },
  {
    id: 'agv',
    text: '正在与车辆控制系统通信',
    status: 'loading',
    isExpanded: false,
    solution: '解决方案：请检查巡检车IP与端口配置是否正确。',
    apiCall: checkAgv
  },
  {
    id: 'cam',
    text: '正在检测摄像头通道状态',
    status: 'loading',
    isExpanded: false,
    solution: '解决方案：请检查摄像头IP及账号密码是否正确。',
    apiCall: checkCam
  }
]);
const abortController = ref<AbortController | null>(null);
const isOk = ref(true);
const checkAll = async () =>{
  abortController.value = new AbortController();
  const signal = abortController.value.signal;

  for (const check of checks.value) {

    if (signal.aborted) {
      console.log('检查流程已被中止，退出循环。');
      return; // 直接退出函数
    }
    try {
      const response = await check.apiCall(signal);

      if (signal.aborted) {
        continue; // 如果已中止，则不更新状态，直接开始下一次循环（或直接返回）
      }

      if (response.data && response.code === 200) {
        check.status = 'success';
      } else {

        check.status = 'error';
        check.isExpanded = true;
        check.errorMessage = response.msg || '检查失败，但未返回具体错误信息。';
      }
    } catch (error: any) {
      if (axios.isCancel(error)) {
        console.log(`API call for "${check.id}" was canceled.`);
        break;
      }
      check.status = 'error';
      check.isExpanded = true;
      let message = '连接失败或服务器无响应。';
      if (error.response && error.response.data && error.response.data.msg) {
        message = error.response.data.msg;
      } else if (error.message) {
        message = error.message;
      }
      check.errorMessage = message;
    }

  }
  isOk.value = !checks.value.every(check => check.status === 'success')
}
const recheck = () => {
  isOk.value = true;
  if (abortController.value) {
    abortController.value.abort();
  }
  for(const check of checks.value){
    check.status = 'loading';
    check.isExpanded = false;
    check.errorMessage = undefined;
  }
  checkAll()
}
onMounted( () => {
  checkAll()
});




</script>

<template>
  <div style="align-items: center;height: 100vh;display: flex">
    <el-card header="AGV智能巡检系统" style="text-align: center;font-size: 25px;width: 400px;margin: auto;font-weight: bold;">
      <el-form style="padding: 30px">

        <div v-for="check in checks" :key="check.id" class="check-item" :class="{ expanded: check.isExpanded }">
          <div class="check-header">
            <div class="check-icon" :class="check.status">
              <template v-if="check.status === 'loading'">⟳</template>
              <template v-if="check.status === 'success'">✓</template>
              <template v-if="check.status === 'error'">✕</template>
            </div>
            <span>{{ check.text }}</span>
          </div>
          <div class="check-content">
            {{ check.solution }}
          </div>
        </div>

        <el-form-item style="margin-top: 40px">
          <div style="display: flex;margin: auto">
            <router-link to="/setting" style="text-decoration: none;">
              <el-button style="border-radius: 50%;width: 40px;height: 40px;display: flex; align-items: center;justify-content: center;padding: 0;">⚙</el-button>
            </router-link>
            <router-link to="/task" style="text-decoration: none">
              <el-button type="success" style="height: 40px;margin-left: 10px" :disabled = "isOk">进入系统</el-button>
            </router-link>
            <el-button type="primary" @click = 'recheck' style="height: 40px;margin-left: 10px">重新检测</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.check-item {
  border: 1px solid #ddd;
  margin-bottom: 10px;
  border-radius: 4px;
  font-size: 16px;
  font-weight: normal;
}

.check-header {
  padding: 12px 16px;
  background: #fafafa;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
}

.check-icon {
  width: 20px;
  height: 20px;
  margin-right: 10px;
  border-radius: 50%;
  border: 2px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.check-icon.loading {
  border-color: #409eff;
  animation: spin 1s linear infinite;
}

.check-icon.success {
  border-color: #67c23a;
  background: #67c23a;
  color: white;
}

.check-icon.error {
  border-color: #f56c6c;
  background: #f56c6c;
  color: white;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.check-content {
  padding: 12px 16px;
  display: none;
  background: #fff;
  color: #666;
  font-size: 14px;
}

.check-item.expanded .check-content {
  display: block;
}

</style>